package cn.itsource.pethome.org.service.impl;

import cn.itsource.pethome.base.service.impl.BaseServiceImpl;
import cn.itsource.pethome.org.domain.Department;
import cn.itsource.pethome.org.mapper.DepartmentMapper;
import cn.itsource.pethome.org.service.IDepartmentService;
import cn.itsource.pethome.base.util.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


 /*   @Override
    public PageInfo<Department> findPageByQuery(DepartmentQuery departmentQuery){
        //总条数
        Long total = departmentMapper.findCount(departmentQuery);
        //如果总条数为0，就没必要查询分页列表了
        if(total.equals(0L)){
            return new PageInfo<Department>();
        }
        //查询分页列表
        List<Department> list = departmentMapper.findListByQuery(departmentQuery);
        //把总条数和分页列表，封装成PageInfo对象
        return new PageInfo<Department>(list, total);
    }
*/

    public void findTree(List<Department> departments){
        if(departments.size()!=0){  //如果有值
            for (Department department : departments){
                //通过parentId查询子部门
                List<Department> list = departmentMapper.findByParentId(department.getId());
                if(list.size()!=0){
                    //把结果值查询出来后封装到children中
                    department.setChildren(list);
                    //递归查询以下所有级
                    this.findTree(list);
                }
            }
        }
    }


    //查询部门树
    @Override
    public List<Department> findDepartmentTree() {
        //先查询一级和二级部门
        List<Department> list = departmentMapper.findOneAndTwoLevel();
        //循环所有的一级部门（二级部门封装到children里了）
        for (Department department:list){
            //拿到所有的二级部门
            List<Department> children = department.getChildren();
            //如果子节点长度为0
            if(children.size()==0){
                //我就要设置children为null，否则前端展示的时候就有下一级的图标（但实际是没有下一级的）
                department.setChildren(null);
            }
            //拿着二级部门的id找三级部门；从二级部门开始循环

            this.findTree(children);
        }
        return list;
    }
}
